import { isArray, isPlainObject } from "../utils/utils";
import store from "./../store/index"
const hasOwnProperty = Object.prototype.hasOwnProperty;
const hasOwn = (val, key) => hasOwnProperty.call(val, key);

export const getFieldMap = (fields) => {
  const fieldMap = Object.create(null);
  /**
   * 返回一个给定对象自身可枚举属性的键值对数组，
   * 其排列与使用 for...in 循环遍历该对象时返回的顺序一致
   */
  for (const [key, fc] of Object.entries(fields)) {
    fieldMap[key] = fc.map || key;
  }
  return fieldMap;
};

export const setFieldStatus = (fieldsMap) => {
  return Object.keys(fieldsMap).reduce((prev, curr) => {
    prev[curr] = status;
    return prev;
  }, Object.create(null));
};

export const checkDataSchema = (data, fields) => {
  let _data = null;
  if (isPlainObject(data)) {
    _data = data;
  } else if (isArray(data)) {
    _data = data[0];
  }
  return Object.entries(fields)
    .reduce((prev, [key, fc]) => {
      if (_data && hasOwn(_data, fc.map || key)) {
        prev[key] = "success";
      } else if (fc.optional) {
        prev[key] = "optional";
      } else {
        prev[key] = "failed";
      }
      return prev;
    }, Object.create(null));
};

export const setMyData = async (comId, apiName, apiConfig, apiDataConfig) => {
  await store.dispatch("debug/setFieldStatus",{comId,fields:setFieldStatus()})
};